package com.dreamchaser.familydevice.util.QYWeChat.service.impl;


import com.alibaba.fastjson.JSON;
import com.dreamchaser.familydevice.util.QYWeChat.WeChatUtil;
import com.dreamchaser.familydevice.util.QYWeChat.service.IQYWeChatNewsService;
import com.dreamchaser.familydevice.util.QYWeChat.service.IwxHandle;
import com.dreamchaser.familydevice.util.QYWeChat.service.WechatPush;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;


import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

/**
 * 处理企业微信回调业务
 */
@Slf4j
public class QYWeChatNewsService implements IQYWeChatNewsService {

    public IwxHandle handle;

    public QYWeChatNewsService(IwxHandle handle) {
        this.handle = handle;
    }


    @Override
    public void sendMessage(String xml, WeChatUtil weChatUtil) throws RuntimeException{
        // 解析xml
        // 创建saxReader对象
        SAXReader reader = new SAXReader();
        WechatPush wechatPush = new WechatPush();
        // 通过read方法读取一个文件 转换成Document对象
        Document document = null;
        try {
            document = reader.read(new ByteArrayInputStream(xml.getBytes("UTF-8")));
            //获取根节点元素对象
            Element node = document.getRootElement();
            // 获取node节点中，子节点的元素名称为supercars的元素节点。
            // 获取发送者
            Element fromUserEl = node.element("FromUserName");
            wechatPush.fromUser = fromUserEl.getText();
            // 获取企业应用的id
            Element agentIDEl = node.element("AgentID");
            wechatPush.agentId = agentIDEl.getText();
            // 获取消息类型
            Element msgType1 = node.element("MsgType");
            wechatPush.msgType = msgType1.getText();
            log.info("消息处理");
            if (wechatPush.msgType.equals("text")) {
                // 获取内容
                Element contentEl = node.element("Content");
                wechatPush.content = contentEl.getText();
                weChatUtil.sendAgentMsg(wechatPush.fromUser + "|ShaJun", Integer.parseInt(wechatPush.agentId), wechatPush.fromUser + "：" + wechatPush.content);
            } else if (wechatPush.msgType.equals("event")) {
                // 获取事件
                Element eventId = node.element("EventKey");
                wechatPush.eventKey = eventId == null ? "" : eventId.getText();


            } else {
                weChatUtil.sendAgentMsg("ShaJun", Integer.parseInt(wechatPush.agentId), wechatPush.fromUser + "：" + xml + wechatPush.msgType);
            }
            log.info("准备处理:"+ JSON.toJSONString(wechatPush));
            if (wechatPush.agentId.equals(WeChatUtil.familyDataAgentId.toString())) {
                handle.run(wechatPush);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
